#    Tichy
#
#    copyright 2008 Guillaume Chereau (charlie137@gmail.com)
#
#    This file is part of Tichy.
#
#    Tichy is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Tichy is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Tichy.  If not, see <http://www.gnu.org/licenses/>.


from object import Object


class Attribute(Object):

    def __init__(self, name, type, value=None):
        super(Attribute, self).__init__()
        self.name = name
        self.attr = '_attr_%s' % self.name
        self.__type = type
        self.value = value

    @property
    def type(self):
        if isinstance(self.__type, str):
            from item import Item
            self.__type = Item.find_by_name(self.__type)
        return self.__type

    def __get__(self, obj, type=None):
        # If we get the attribute from the class we get the attribute
        # itself.
        if obj is None:
            return self
        if not hasattr(obj, self.attr):
            value = self.type()
            value.parent = obj
            setattr(obj, self.attr, Attribute(self.name, self.type, value))
        return getattr(obj, self.attr).value

    def __set__(self, obj, value):
        if not hasattr(obj, self.attr):
            value = self.type(value)
            value.parent = obj
            setattr(obj, self.attr, Attribute(self.name, self.type, value))
        getattr(obj, self.attr).set(obj, value)

    def set(self, obj, value):
        self.value.value = value

    def view(self, parent, editable=False, **kargs):
        from tichy import gui
        from tichy import Text
        # XXX: do this an other way...
        if self.name == 'text':
            return self.value.view(parent, expand=True, editable=editable)
        box = gui.HBox(parent, border=0)
        gui.Label(box, ("%s:" % self.name).rjust(8))
        if editable:
            self.value.create_actor().view(box, expand=True)
        else:
            self.value.view(box, expand=True)
        return box
